package store.wetravel.web.user.action;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import store.wetravel.common.Const;
import store.wetravel.common.ServerResponse;
import store.wetravel.common.TokenCache;
import store.wetravel.pojo.User;
import store.wetravel.web.user.service.IUserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * Created by xinlong on 2017/10/14.
 */
@Controller
@RequestMapping("/user/")
public class UserController {

    @Resource(name="iUserService")
    IUserService iUserService;

    @RequestMapping("get_user_info.do")
    @ResponseBody
    public ServerResponse<User> getUserInfo(HttpSession session){
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if(user != null){
            return ServerResponse.createBySuccess(user);
        }
        return ServerResponse.createByErrorMessage("用户未登录，无法获取当前用户信息");
    }

    @RequestMapping("logout.do")
    @ResponseBody
    public ServerResponse<String> logout(HttpSession session){
        session.removeAttribute(Const.CURRENT_USER);
        return ServerResponse.createBySuccessMessage("退出登录成功");
    }

    @RequestMapping("login.do")
    @ResponseBody
    public ServerResponse<String> login(String username, String password, HttpSession session){
        ServerResponse response = iUserService.login(username, password);
        if(response.isSuccess()){
            session.setAttribute(Const.CURRENT_USER,response.getData());
        }
        return response;
    }

    @RequestMapping("register.do")
    @ResponseBody
    public ServerResponse<String> register(User user){
        return iUserService.register(user);
    }

    @RequestMapping("checkValid.do")
    @ResponseBody
    public ServerResponse<String> checkValid(String str,String type){
        return iUserService.checkValid(str,type);
    }

//    @RequestMapping("forget_get_question.do")
//    @ResponseBody
//    //获取忘记密码问题
//    public ServerResponse<String> forgetGetQuestion(String username,HttpSession session){
//        if(username==null || username.equals("")){
//            return ServerResponse.createByErrorMessage("用户名为空");
//        }
//        ServerResponse response = iUserService.forgetGetQuestion(username);
//        if(response.isSuccess()){
//            session.setAttribute(Const.CURRENT_FORGETUSERNAME,username);
//        }
//        return response;
//    }
//
//    @RequestMapping("checkAnswer.do")
//    @ResponseBody
//    //确认忘记密码问题的答案
//    public ServerResponse<String> checkAnswer(String answer,HttpSession session){
//        String username = (String)session.getAttribute(Const.CURRENT_FORGETUSERNAME);
//        String question = (String)session.getAttribute(Const.CURRENT_FORGETQUESTION);
//        if(StringUtils.isBlank(username)||StringUtils.isBlank(question)||StringUtils.isBlank(answer)){
//            return ServerResponse.createByErrorMessage("参数为空");
//        }
//        ServerResponse response = iUserService.checkAnswer(username,question,answer);
//        if(response.isSuccess()){
//            //此处将业务层的token放入session中保存，不传给前端
//            session.setAttribute(Const.CURRENT_FORGETTOKENCACHE,response.getData());
//            response.clearData();
//            return response;
//        }
//        return response;
//    }

    /**
     * 重置密码并返回状态的json
     */
    @RequestMapping("reset_password.do")
    @ResponseBody
    public ServerResponse<String> resetPassword(String password,HttpSession session){
        String username = (String)session.getAttribute(Const.CURRENT_FORGETUSERNAME);
        String tokenCache = (String)session.getAttribute(Const.CURRENT_FORGETTOKENCACHE);
        ServerResponse<String> response= iUserService.resetPassword(username,password,tokenCache);
        System.out.println("status:"+response.getStatus());
        System.out.println("data:"+response.getData());
        System.out.println("msg:"+response.getMsg());
        //如果修改密码成功清除session中相关数据及token
        if(response.getStatus()==0){
            TokenCache.removeKey(TokenCache.TOKEN_PREFIX+username);
            session.removeAttribute(Const.CURRENT_FORGETUSERNAME);
            session.removeAttribute(Const.CURRENT_FORGETQUESTION);
            session.removeAttribute(Const.CURRENT_FORGETTOKENCACHE);
        }
        return response;
    }

    @RequestMapping("register")
    public String registerPage(){
        return "user/register";
    }

    @RequestMapping("login")
    public String loginPage(){
        return "user/login";
    }

    /**
     * 跳转至用户信息页
     */
    @RequestMapping("userInfo")
    public String userInfoPage(HttpSession session){
        User user = (User)session.getAttribute(Const.CURRENT_USER);
        if(user != null){
            return "user/userInfo";
        }
        return "user/login";
    }

    /**
     * 跳转至找回密码页
     */
    @RequestMapping("forget")
    public String forgetPage(){
        return "user/forget";
    }

    /**
     * 跳转至验证找回密码答案页
     * @param username
     * @param session
     * @param attr
     * @return
     */
    @RequestMapping("checkAnswer")
    public String checkAnswerPage(String username, HttpSession session,RedirectAttributes attr){
        String sessionScopeUsername = (String)session.getAttribute(Const.CURRENT_FORGETUSERNAME);
        //此处判断sessionScope中的用户名是为了防止在确认找回密码答案时答案错误而重定向到该页时因为request中没有用户名这个参数而返回上级页面
        if((username==null || username.equals(""))&&(sessionScopeUsername==null || sessionScopeUsername.equals(""))){
            attr.addFlashAttribute(Const.RESPONSE,ServerResponse.createByErrorMessage("用户名为空"));
            return "redirect:/user/forget";
        }
        //作用同上，防止防止在确认找回密码答案时答案错误而重定向到该页时因为request中没有用户名这个参数而获取问题失败
        if(username==null || username.equals("")){
            username = sessionScopeUsername;
        }
        ServerResponse response = iUserService.forgetGetQuestion(username);
        if(response.isSuccess()){
            session.setAttribute(Const.CURRENT_FORGETUSERNAME,username);
            session.setAttribute(Const.CURRENT_FORGETQUESTION,response.getData());
            return "user/checkAnswer";
        }
        attr.addFlashAttribute(Const.RESPONSE,response);
        return "redirect:/user/forget";
    }

    /**
     * 跳转至重置密码页
     * @param answer
     * @param session
     * @param attr
     * @return
     */
    @RequestMapping("resetPassword")
    public String resetPasswordPage(String answer,HttpSession session,RedirectAttributes attr){
        String username = (String)session.getAttribute(Const.CURRENT_FORGETUSERNAME);
        String question = (String)session.getAttribute(Const.CURRENT_FORGETQUESTION);
        if(StringUtils.isBlank(username)||StringUtils.isBlank(question)){
            attr.addFlashAttribute(Const.RESPONSE,ServerResponse.createByErrorMessage("用户名或找回密码问题为空"));
            return "redirect:/user/forget";
        }
        System.out.println("resetPassword:验证用户名及找回密码问题通过");
        ServerResponse response = iUserService.checkAnswer(username,question,answer);
        if(response.isSuccess()){
            session.setAttribute(Const.CURRENT_FORGETTOKENCACHE,response.getData());
            return "user/resetPassword";
        }
        System.out.println("resetPassword:验证找回密码答案失败");
        attr.addFlashAttribute(Const.RESPONSE,response);
        return "redirect:/user/checkAnswer";
    }

    @RequestMapping("testRedirect")
    public String testRedirect(){
        //通过redirect只能获取webapp内除了WEB-INF的资源
        return "redirect:/testRedirect.html";
    }

    @RequestMapping("testForward")
    public String testForward(){
        //可以通过forward获取到WEB-INF内的资源
        return "forward:/WEB-INF/testForward.html";
    }


}
